<?php

namespace App\Service\ServiceTrait;

use App\Cache\RedisKey;
use App\Constants\AccostBusinesswomen;
use App\Helpers\RedisUtil;
use Redis;
use RedisException;

trait AccostTrait
{
    /**
     * @return void
     */
    protected function getRedis()
    {
        $this->redis = RedisUtil::getRedis();

        $this->lockKey = RedisKey::userRecommendLock($this->actionUserId);
        $this->numKey = RedisKey::userRecommendNum($this->actionUserId);
        $this->key = RedisKey::userRecommendKey($this->actionUserId);
    }

    /**
     * 检测缓存条件是否达到标准
     * @return bool true=正常搭讪 false=不能搭讪
     * @throws RedisException
     */
    protected function checkCacheCondition(): bool
    {
        //是否已存在锁定的key
        if ($this->redis->exists($this->lockKey)) {
            return false;
        }

//        //是否存在数量key并且数量key大于人数
//        if ($this->redis->exists($this->numKey) == 1 && $this->redis->get($this->numKey) >= AccostBusinesswomen::CONDITION_NUMBER) {
//            return false;
//        }

        return true;
    }

    /**
     * 获取推荐数据
     * @return array|Redis
     * @throws RedisException
     */
    protected function getUserRecommendData()
    {
        $interval = AccostBusinesswomen::RECOMMEND_TIME * 3600;

        $script = <<<lua
            local recommendList = redis.call('exists',KEYS[1])
            if recommendList == 1 then
                return redis.call('sMembers',KEYS[1])
            end
            
            redis.call('sAdd',KEYS[1],0)
            redis.call('Expire',KEYS[1],ARGV[1])
            return {0}
        lua;

        $res = $this->redis->eval($script, [$this->key, $interval], 1);

        return array_diff($res, [0]);
    }

    /**
     * 获取屏蔽的用户
     * @return array|Redis
     * @throws RedisException
     */
    protected function getExcludeUsers()
    {
        $key = RedisKey::appHiddenUser();

        $redis = RedisUtil::getRedis();

        return $redis->sMembers($key);
    }
}
